package com.ev.apis.controller.asl;


import com.ev.asl.domain.AslReportWorkDO;
import com.ev.asl.domain.MoldingDailyDO;
import com.ev.asl.dto.AslReportWorkParam;
import com.ev.asl.service.AslReportWorkService;
import com.ev.asl.service.KisBillOfPushService;
import com.ev.asl.service.MoldingProductionInstructionService;
import com.ev.asl.vo.ApiResultVO2S;
import com.ev.asl.vo.AslReportWorkVo;
import com.ev.framework.annotation.EvApiByToken;
import com.ev.framework.config.Constant;
import com.ev.framework.exception.BDException;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.mes.dao.ProductionFeedingDetailDao;
import com.ev.mes.domain.SyncLogDO;
import com.ev.scm.domain.StockInDO;
import com.ev.scm.domain.StockInItemDO;
import com.ev.system.domain.UserDO;
import com.ev.system.service.UserService;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@RestController
@Slf4j
public class AslReportWorkController {
    @Resource
    private AslReportWorkService aslReportWorkService;

    @Autowired
    private UserService userService;

    @Autowired
    private KisBillOfPushService kisBillOfPushService;

    @Autowired
    private ProductionFeedingDetailDao productionFeedingDetailDao;

    @Autowired
    private MoldingProductionInstructionService moldingProductionInstructionService;




    @EvApiByToken(value = "/apis/report/add", method = RequestMethod.POST, apiTitle = "新增报工")
    public R add(@RequestBody AslReportWorkDO aslReportWorkDO) {
        String[] userIds = aslReportWorkDO.getUserId().split(",");
        StringBuilder sb = new StringBuilder();
        for (String userId : userIds) {
            if(sb.length() > 0){
                sb.append(",");
            }
            sb.append(userService.get(Long.valueOf(userId)).getName());
        }
        aslReportWorkDO.setUserName(sb.toString());
        aslReportWorkService.save(aslReportWorkDO);
        Map<String, Object> moldingProductionInstructionDO = moldingProductionInstructionService.getDetail(aslReportWorkDO.getMpiId().longValue());
        Object planId = moldingProductionInstructionDO.get("planId");
        UserDO userDO = userService.get(275L);//丁顺
        StockInDO stockIn = new StockInDO();
        stockIn.setOperator(userDO.getUserId());
        stockIn.setSourceCompany(userDO.getDeptId());
        ArrayList<SyncLogDO> syncLogDOS = new ArrayList<>();
        if (ObjectUtils.isEmpty(planId)){
            log.error("未找到生产指示的生产计划，不同步金蝶===========================");
            return R.error(500,"报工异常：未找到生产指示的生产计划，不同步金蝶");
        }else {
            SyncLogDO syncLogDO = new SyncLogDO();
            String content = "报工成品入库";
            syncLogDO.setContent(content);
            syncLogDO.setType(2);
            syncLogDOS.add(syncLogDO);
            //合格数量：入库车间库
            if (!ObjectUtils.isEmpty(aslReportWorkDO.getQuantity()) && aslReportWorkDO.getQuantity().compareTo(BigDecimal.ZERO) > 0){
                List<StockInItemDO> qualifiedCollect = new ArrayList<>();
                StockInItemDO itemDO = new StockInItemDO();
                itemDO.setMaterielId((Long)moldingProductionInstructionDO.get("materielId"));
                itemDO.setWarehouse(Constant.warehouse4);//成品库
                itemDO.setCount(aslReportWorkDO.getQuantity());
                itemDO.setSourceInteridEntryid(moldingProductionInstructionDO.get("planId").toString());
                itemDO.setBatch(aslReportWorkDO.getBatchNo());
                itemDO.setSourceCode(moldingProductionInstructionDO.get("planNo").toString());
                itemDO.setUuid(UUID.randomUUID().toString());
                qualifiedCollect.add(itemDO);
                log.error("==========================合格数量：入库车间库======================================");
                log.error("==========================合格数量：userDO:{}======================================",userDO);
                Triple<Boolean, String, String> triple = kisBillOfPushService.inputTypeParamConversionSync2(1, 2, qualifiedCollect,stockIn, userDO);
                if (!triple.getLeft()) {
                    productionFeedingDetailDao.batchSaveSyncLog(syncLogDOS);
                    throw new BDException(triple.getMiddle());
                }
                Triple<Boolean, String, ApiResultVO2S> checkResult = kisBillOfPushService.checkK3In(ShiroUtils.getUser().getToken(), triple.getRight(), ShiroUtils.getUser().getName(),true);
                if (!checkResult.getLeft()) {
                    productionFeedingDetailDao.batchSaveSyncLog(syncLogDOS);
                    throw new BDException(triple.getMiddle());
                }
            }
        }
        return R.ok();
    }

    @EvApiByToken(value = "/apis/report/list", method = RequestMethod.POST, apiTitle = "获取报工列表信息")
    public R list(@RequestBody AslReportWorkParam param) {
        Object vos = aslReportWorkService.pageList(param);
        return R.ok().put("data", vos);
    }

    @EvApiByToken(value = "/apis/report/getById", method = RequestMethod.GET, apiTitle = "获取报工数据")
    public R getById(@ApiParam(value = "获取报工数据", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        AslReportWorkDO aslReportWorkDO = aslReportWorkService.getById(id);
        String[] userIds = aslReportWorkDO.getUserId().split(",");
        StringBuilder sb = new StringBuilder();
        for (String userId : userIds) {
            if(sb.length() > 0){
                sb.append(",");
            }
            sb.append(userService.get(Long.valueOf(userId)).getName());
        }
        aslReportWorkDO.setUserName(sb.toString());
        return R.ok().put("data",aslReportWorkDO);
    }

    @EvApiByToken(value = "/apis/report/getByshift", method = RequestMethod.POST, apiTitle = "获取当日班次报工数据")
    public R getByshift(@ApiParam(value = "获取当日班次报工数据", required = true) @RequestParam(value = "mGroup", defaultValue = "") Integer shift,
                        @ApiParam(value = "接收人") @RequestParam(value = "mpiId", required = true) Long mpiId,
                        @ApiParam(value = "开始时间") @RequestParam(value = "startTime", required = true) Date startTime,
                        @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = true) Date endTime
                        ) {
        AslReportWorkVo vo= aslReportWorkService.getByshift(shift,mpiId,startTime,endTime);
        return R.ok().put("data",vo);
    }

}
